/**
 * 
 */
package cn.com.winning.ecare.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.common.MyCommPopupWindowAdapter;
import cn.com.winning.ecare.common.PullDownView;
import cn.com.winning.ecare.common.PullDownView.OnPullDownListener;
import cn.com.winning.ecare.model.Node;
import cn.com.winning.ecare.utils.DisplayUtil;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.StringUtil;
import cn.com.winning.ecare.utils.URLUtils;
import cn.com.winning.ecare.widgets.CustomProgressDialog;

/**排队查询
 * @author ZJJ
 */
public class QueueUp extends Activity implements OnPullDownListener, OnItemClickListener
{

	private QueueUp oThis = this;
	private static final int WHAT_DID_LOAD_DATA_ERR = -1;
	private static final int WHAT_DID_LOAD_DATA = 0;
	private static final int WHAT_DID_REFRESH = 1;
	private static final int WHAT_DID_MORE = 2;
	private static final int WHAT_DID_LOAD_CHSSSELECTDATA = 3;
	private ListView commListView;
	private List<Node> listcomm = new ArrayList<Node>();
	AlertDialog alert_comm_popupWindow = null;
	private PullDownView mPullDownView;
	private ListView mListView;
	private List<Map<String, Object>> listmain = new ArrayList<Map<String, Object>>();
	// 分页加载
	private int pageSize = 20;
	private static final int pageLoadMore = 20;
	private MyApplication myApplication;
	private ImageButton menuButton, mainselected;
	MyCommPopupWindowAdapter myCommPopupWindowAdapter = null;
	private TextView queueupmain_title;
	MyAdapter myAdapter = null;
	private String code = "";
	CustomProgressDialog proDialog;// 加载框

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.queueupmain);
		myApplication = (MyApplication) getApplication();
		myApplication.addActivity(this);
		/*
		 * 1.使用PullDownView 2.设置OnPullDownListener 3.从mPullDownView里面获取ListView
		 */
		mPullDownView = (PullDownView) findViewById(R.id.queuemain_pull_down_view);
		mPullDownView.setOnPullDownListener(this);
		mListView = mPullDownView.getListView();
		mListView.setDivider(null);
		findView();
		setListener();
		proDialog = CustomProgressDialog.createDialog(oThis);
		proDialog.setMessage("数据加载中...");
		proDialog.show();
		proDialog.setCanceledOnTouchOutside(false);
		new Thread(new InitData_()).start();
		new Thread(new InitSelectData_()).start();
	}

	private void findView()
	{
		menuButton = (ImageButton) findViewById(R.id.menuButton);
		mainselected = (ImageButton) findViewById(R.id.mainselected);
		queueupmain_title = (TextView) findViewById(R.id.queueupmain_title);
	// 读取缓存数据,如果缓存有数据，则读取缓存
		SharedPreferences settings = getSharedPreferences("yyxx_file", 0);
		queueupmain_title.setText(settings.getString("pdcxname", "挂号叫号"));
		code = settings.getString("pdcxid", "01");
	}

	private void setListener()
	{

		menuButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				oThis.onBackPressed();
			}
		});
		mainselected.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent();
				intent.setClass(oThis, Mainmean.class);
				startActivity(intent);
				oThis.finish();
			}
		});

		queueupmain_title.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{

				int[] xy = new int[2];
				v.getLocationOnScreen(xy);
				int x = xy[0];
				int y = xy[1] + v.getHeight();
				initCommPopupWindow(v, x, y);
				commListView.setOnItemClickListener(new OnItemClickListener()
				{

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
					{

						Node n = (Node) arg0.getItemAtPosition(arg2);
						queueupmain_title.setText(n.getText());
						code = n.getCode();
						alert_comm_popupWindow.dismiss();
						// 把地区及医院信息加入缓存
						SharedPreferences settings = getSharedPreferences("yyxx_file", 0);
						// 获得可编辑对象
						SharedPreferences.Editor editor = settings.edit();
						editor.putString("pdcxid", n.getCode().toString());
						editor.putString("pdcxname", n.getText().toString());
						editor.commit();
						proDialog = CustomProgressDialog.createDialog(oThis);
						proDialog.setMessage("数据加载中...");
						proDialog.show();
						proDialog.setCanceledOnTouchOutside(false);
						new Thread(new InitData_()).start();
					}
				});
				myCommPopupWindowAdapter.notifyDataSetChanged();
			}
		});

	}

	private void onLoad()
	{
		mPullDownView.notifyDidLoad();
		mPullDownView.notifyDidRefresh();
		mPullDownView.notifyDidMore();
		mPullDownView.enableAutoFetchMore(true, 1);
	}

	private Handler myHandler = new Handler()
	{

		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			switch (msg.what)
			{
				case WHAT_DID_LOAD_DATA_ERR:
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					Toast.makeText(oThis, (String) msg.obj, Toast.LENGTH_SHORT).show();
					listmain.clear();
					myAdapter = new MyAdapter();
					mListView.setAdapter(myAdapter);
					myAdapter.notifyDataSetChanged();
					mListView.removeFooterView(mPullDownView.getmFooterView());
					onLoad();
					break;
				case WHAT_DID_LOAD_DATA:
				{
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					if (msg.obj != null)
					{
						listmain = (List<Map<String, Object>>) msg.obj;
					}
					myAdapter = new MyAdapter();
					mListView.setAdapter(myAdapter);
					myAdapter.notifyDataSetChanged();
					onLoad();
					break;
				}
				case WHAT_DID_REFRESH:
				{
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					if (msg.obj != null)
					{
						listmain = (List<Map<String, Object>>) msg.obj;
					}
					myAdapter.notifyDataSetChanged();
					onLoad();
					break;
				}

				case WHAT_DID_MORE:
				{
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					if (msg.obj != null)
					{
						listmain = (List<Map<String, Object>>) msg.obj;
					}
					myAdapter.notifyDataSetChanged();
					onLoad();
					break;
				}
				case WHAT_DID_LOAD_CHSSSELECTDATA:
				{
					if (msg.obj != null)
					{
						listcomm = (List<Node>) msg.obj;
					}
					break;
				}
			}

		}

	};

	private void initData()
	{
		Message msg = myHandler.obtainMessage();
		List<Map<String, Object>> templist = new ArrayList<Map<String, Object>>();
		JSONArray jsonArr;
		List<NameValuePair> ls = new ArrayList<NameValuePair>();
		ls.add(new BasicNameValuePair("lbdm", StringUtil.isEmpty(code) ? "01" : code));
		ls.add(new BasicNameValuePair("sfzh", myApplication.getSfzh()));
		JSONObject json = HTTPGetTool.getTool().post(URLUtils.HOST + URLUtils.URLFINDJHMX, ls);
		try
		{
			if (json != null)
			{
				jsonArr = new JSONArray(json.getString("jsonstrgh"));
				for (int i = 0; i < jsonArr.length(); i++)
				{
					JSONObject jsonObject = jsonArr.getJSONObject(i);
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("hzxm", jsonObject.getString("hzxm"));
					map.put("sfzh", jsonObject.getString("sfzh"));
					map.put("ghhx", jsonObject.getString("ghhx"));
					map.put("ghrq", jsonObject.getString("ghrq"));
					map.put("ksdm", jsonObject.getString("ksdm"));
					map.put("ksmc", jsonObject.getString("ksmc"));
					map.put("ysmc", jsonObject.getString("ysmc"));
					map.put("ghlb", jsonObject.getString("ghlb"));
					map.put("jhzt", jsonObject.getString("jhzt"));
					templist.add(map);
				}
				if (templist.size() > 0)
				{
					msg.what = WHAT_DID_LOAD_DATA;
					msg.obj = templist;
				}
				else
				{
					msg.what = WHAT_DID_LOAD_DATA_ERR;
					msg.obj = "暂无数据";
				}

			}
			else
			{
				msg.what = WHAT_DID_LOAD_DATA_ERR;
				msg.obj = "暂无数据";
			}

		}
		catch (Exception e)
		{
			msg.what = WHAT_DID_LOAD_DATA_ERR;
			msg.obj = "暂无数据";
		}
		myHandler.sendMessage(msg);
	}

	private void refreshData()
	{
		Message msg = myHandler.obtainMessage();
		List<Map<String, Object>> templist = new ArrayList<Map<String, Object>>();
		JSONArray jsonArr;
		List<NameValuePair> ls = new ArrayList<NameValuePair>();
		ls.add(new BasicNameValuePair("lbdm", StringUtil.isEmpty(code) ? "01" : code));
		ls.add(new BasicNameValuePair("sfzh", myApplication.getSfzh()));
		JSONObject json = HTTPGetTool.getTool().post(URLUtils.HOST + URLUtils.URLFINDJHMX, ls);
		try
		{
			if (json != null)
			{
				jsonArr = new JSONArray(json.getString("jsonstrgh"));
				for (int i = 0; i < jsonArr.length(); i++)
				{
					JSONObject jsonObject = jsonArr.getJSONObject(i);
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("hzxm", jsonObject.getString("hzxm"));
					map.put("sfzh", jsonObject.getString("sfzh"));
					map.put("ghhx", jsonObject.getString("ghhx"));
					map.put("ghrq", jsonObject.getString("ghrq"));
					map.put("ksdm", jsonObject.getString("ksdm"));
					map.put("ksmc", jsonObject.getString("ksmc"));
					map.put("ysmc", jsonObject.getString("ysmc"));
					map.put("ghlb", jsonObject.getString("ghlb"));
					map.put("jhzt", jsonObject.getString("jhzt"));
					templist.add(map);
				}

				if (templist.size() > 0)
				{
					msg.what = WHAT_DID_LOAD_DATA;
					msg.obj = templist;
				}
				else
				{
					msg.what = WHAT_DID_LOAD_DATA_ERR;
					msg.obj = "暂无更多数据";
				}
			}
			else
			{
				msg.what = WHAT_DID_LOAD_DATA_ERR;
				msg.obj = "暂无数据";
			}

		}
		catch (Exception e)
		{
			msg.what = WHAT_DID_LOAD_DATA_ERR;
			msg.obj = "暂无数据";
		}
		myHandler.sendMessage(msg);
	}

	private void loadMoreData()
	{
		Message msg = myHandler.obtainMessage();
		List<Map<String, Object>> templist = new ArrayList<Map<String, Object>>();
		JSONArray jsonArr;
		List<NameValuePair> ls = new ArrayList<NameValuePair>();
		ls.add(new BasicNameValuePair("lbdm", StringUtil.isEmpty(code) ? "01" : code));
		ls.add(new BasicNameValuePair("sfzh", myApplication.getSfzh()));
		JSONObject json = HTTPGetTool.getTool().post(URLUtils.HOST + URLUtils.URLFINDJHMX, ls);
		try
		{
			if (json != null)
			{
				jsonArr = new JSONArray(json.getString("jsonstrgh"));
				for (int i = 0; i < jsonArr.length(); i++)
				{
					JSONObject jsonObject = jsonArr.getJSONObject(i);
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("hzxm", jsonObject.getString("hzxm"));
					map.put("sfzh", jsonObject.getString("sfzh"));
					map.put("ghhx", jsonObject.getString("ghhx"));
					map.put("ghrq", jsonObject.getString("ghrq"));
					map.put("ksdm", jsonObject.getString("ksdm"));
					map.put("ksmc", jsonObject.getString("ksmc"));
					map.put("ysmc", jsonObject.getString("ysmc"));
					map.put("ghlb", jsonObject.getString("ghlb"));
					map.put("jhzt", jsonObject.getString("jhzt"));
					templist.add(map);
				}

				if (templist.size() > 0)
				{
					msg.what = WHAT_DID_LOAD_DATA;
					msg.obj = templist;
				}
				else
				{
					msg.what = WHAT_DID_LOAD_DATA_ERR;
					msg.obj = "暂无数据";
				}
			}
			else
			{
				msg.what = WHAT_DID_LOAD_DATA_ERR;
				msg.obj = "暂无数据";
			}

		}
		catch (Exception e)
		{
			msg.what = WHAT_DID_LOAD_DATA_ERR;
			msg.obj = "暂无数据";
		}
		myHandler.sendMessage(msg);
	}

	class InitData_ implements Runnable
	{

		@Override
		public void run()
		{

			Looper.prepare();
			initData();
			Looper.loop();
		}

	}

	class RefreshData_ implements Runnable
	{

		@Override
		public void run()
		{

			Looper.prepare();
			refreshData();
			Looper.loop();
		}

	}

	class LoadMoreData_ implements Runnable
	{

		@Override
		public void run()
		{

			Looper.prepare();
			loadMoreData();
			Looper.loop();
		}

	}

	/**
	 * 自定义listview布局显示内容 个人档案界面自定义显示内容
	 * 
	 * @author zjj
	 */
	class MyAdapter extends BaseAdapter
	{

		public int getCount()
		{

			return listmain.size();
		}

		public Object getItem(int position)
		{

			return listmain.get(position);
		}

		public long getItemId(int position)
		{

			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent)
		{

			ViewHolder holder = null;

			if (convertView == null)
			{

				holder = new ViewHolder();

				convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.queueupitem, null);

				holder.queueupitem_ghhx = (TextView) convertView.findViewById(R.id.queueupitem_ghhx);
				holder.queueupitem_ghrq = (TextView) convertView.findViewById(R.id.queueupitem_ghrq);
				holder.queueupitem_hzxm = (TextView) convertView.findViewById(R.id.queueupitem_hzxm);
				holder.queueupitem_sfzh = (TextView) convertView.findViewById(R.id.queueupitem_sfzh);
				holder.queueupitem_ksmc = (TextView) convertView.findViewById(R.id.queueupitem_ksmc);
				holder.queueupitem_ghlb = (TextView) convertView.findViewById(R.id.queueupitem_ghlb);
				holder.queueupitem_ysmc = (TextView) convertView.findViewById(R.id.queueupitem_ysmc);
				holder.queueupitem_jhzt = (TextView) convertView.findViewById(R.id.queueupitem_jhzt);
				convertView.setTag(holder);

			}

			else
			{
				holder = (ViewHolder) convertView.getTag();

			}
			holder.queueupitem_ghhx.setText("挂号序号:" + listmain.get(position % listmain.size()).get("ghhx").toString());
			holder.queueupitem_ghrq.setText("挂号日期:" + listmain.get(position % listmain.size()).get("ghrq").toString());
			holder.queueupitem_hzxm.setText("患者姓名:" + listmain.get(position % listmain.size()).get("hzxm").toString());
			holder.queueupitem_sfzh.setText("身份证号:" + listmain.get(position % listmain.size()).get("sfzh").toString());
			holder.queueupitem_ksmc.setText("挂号科室:" + listmain.get(position % listmain.size()).get("ksmc").toString());
			holder.queueupitem_ghlb.setText("挂号类别:" + listmain.get(position % listmain.size()).get("ghlb").toString());
			holder.queueupitem_ysmc.setText("医生姓名:"
					+ (StringUtil.isEmpty(listmain.get(position % listmain.size()).get("ysmc").toString()) ? "" : listmain
							.get(position % listmain.size()).get("ysmc").toString()));
			holder.queueupitem_jhzt.setText("当前队列:"
					+ (StringUtil.isEmpty(listmain.get(position % listmain.size()).get("jhzt").toString()) ? "" : listmain
							.get(position % listmain.size()).get("jhzt").toString()));
			return convertView;
		}

	}

	static class ViewHolder
	{
		TextView queueupitem_ghhx;
		TextView queueupitem_ghrq;
		TextView queueupitem_hzxm;
		TextView queueupitem_sfzh;
		TextView queueupitem_ksmc;
		TextView queueupitem_ghlb;
		TextView queueupitem_ysmc;
		TextView queueupitem_jhzt;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
	{

	}

	@Override
	public void onRefresh()
	{
		new Thread(new RefreshData_()).start();

	}

	@Override
	public void onMore()
	{
		pageSize = pageSize + pageLoadMore;
		new Thread(new LoadMoreData_()).start();

	}

	// 根据输入框选项获取内容
	class InitSelectData_ implements Runnable
	{

		@Override
		public void run()
		{

			Looper.prepare();
			initSelectData();
			Looper.loop();
		}

	}

	private void initSelectData()
	{
		Message msg = myHandler.obtainMessage();
		List<Node> templist = new ArrayList<Node>();
		List<NameValuePair> ls = new ArrayList<NameValuePair>();
		JSONArray jsonArr;
		JSONObject json = HTTPGetTool.getTool().post(URLUtils.HOST + URLUtils.URLFINDJHLB, ls);
		try
		{
			if (json != null)
			{
				jsonArr = new JSONArray(json.getString("jsonstrlb"));
				for (int i = 0; i < jsonArr.length(); i++)
				{
					JSONObject jsonObject = jsonArr.getJSONObject(i);
					Node n = new Node();
					n.setId(jsonObject.getString("lbbm"));
					n.setCode(jsonObject.getString("lbbm"));
					n.setText(jsonObject.getString("lbmc"));
					templist.add(n);
				}
				msg.what = WHAT_DID_LOAD_CHSSSELECTDATA;
				msg.obj = templist;
			}
			else
			{
				msg.what = WHAT_DID_LOAD_DATA_ERR;
				msg.obj = "暂无数据";
			}
		}
		catch (Exception e)
		{}
		myHandler.sendMessage(msg);
	}

	// 下拉菜单
	private void initCommPopupWindow(View v, int x, int y)
	{
		LayoutInflater flater = oThis.getLayoutInflater();
		final View view = flater.inflate(R.layout.comm_list_popupwindow, null);
		AlertDialog.Builder builder = new AlertDialog.Builder(oThis);
		alert_comm_popupWindow = builder.create();
		alert_comm_popupWindow.setView(view);
		alert_comm_popupWindow.setCanceledOnTouchOutside(false);
		alert_comm_popupWindow.show();
		WindowManager.LayoutParams params = alert_comm_popupWindow.getWindow().getAttributes();
		alert_comm_popupWindow.getWindow().setGravity(Gravity.LEFT | Gravity.TOP);
		params.x = x;
		params.y = y;
		params.width = 200;
		params.height = LayoutParams.WRAP_CONTENT;
		alert_comm_popupWindow.getWindow().setAttributes(params);
		alert_comm_popupWindow.getWindow().setContentView(R.layout.comm_list_popupwindow);
		alert_comm_popupWindow.setCanceledOnTouchOutside(true);
		commListView = (ListView) alert_comm_popupWindow.findViewById(R.id.comm_list_popupwindow_list);
		myCommPopupWindowAdapter = new MyCommPopupWindowAdapter(oThis, listcomm);
		commListView.setAdapter(myCommPopupWindowAdapter);
		myCommPopupWindowAdapter.notifyDataSetChanged();
	}
}
